package com.lw.leetcode.bit.a;

import java.util.Arrays;

/**
 * bit
 * a
 * 1356. 根据数字二进制下 1 的数目排序
 *
 * @Author liw
 * @Date 2021/11/6 22:27
 * @Version 1.0
 */
public class SortByBits {

    public static void main(String[] args) {
        SortByBits test = new SortByBits();

        // [0,1,2,4,8,3,5,6,7]
        int[] arr = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        int[] ints = test.sortByBits(arr);
        System.out.println(Arrays.toString(ints));
    }

    public int[] sortByBits(int[] arr) {
        int length = arr.length;
        for (int i = 0; i < length; i++) {
            int v = arr[i];
            arr[i] = (Integer.bitCount(v) << 20) + v;
        }
        Arrays.sort(arr);
        int t = 0xfffff;
        for (int i = 0; i < length; i++) {
            arr[i] = arr[i] & t;
        }
        return arr;
    }
}
